package qc.module.ehs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.EhsHazardIndentificationResultTypeEnum;
import qc.common.core.enums.EhsRiskEvaluationMethodEnum;
import qc.common.core.enums.EhsRiskLevelEnum;
import qc.common.core.exception.QCPromptException;
import qc.common.core.pair.KeyValuePairDto;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.DateUtil;
import qc.common.core.utils.IdentifierUtil;
import qc.module.ehs.dto.riskevaluation.HazardRiskEvaluationDto;
import qc.module.ehs.dto.riskevaluation.HazardRiskEvaluationMethodDto;
import qc.module.ehs.dto.riskevaluation.HazardRiskEvaluationOptionsItemDto;
import qc.module.ehs.dto.troublecorrect.EhsTroubleCorrectInfoDto;
import qc.module.ehs.entity.EhsHazardInfo;
import qc.module.ehs.entity.EhsHazardRiskEvaluation;
import qc.module.ehs.entity.EhsUnitInfo;
import qc.module.ehs.mapper.EhsHazardRiskEvaluationMapper;
import qc.module.ehs.repository.EhsHazardInfoRepository;
import qc.module.ehs.repository.EhsHazardRiskevlRepository;
import qc.module.ehs.repository.EhsUnitInfoRepository;
import qc.module.platform.dto.uac.UacUserInfoDto;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 危险源风险评价记录信息Service
 *
 * @author QuCheng Tech
 * @create 2024/11/5
 */
@Service
public class EhsHazardRiskevlService {

    @Autowired
    private EhsHazardRiskevlRepository repository;

    @Autowired
    private EhsHazardInfoRepository hazardInfoRepository;

    @Autowired
    private EhsUnitInfoRepository unitInfoRepository;

    @Autowired
    private EhsUnitInfoService unitInfoService;

    @Autowired
    private EhsTroubleCorrectService troubleCorrectService;

    /**
     * 获取风险评价方法
     *
     * @return List<HazardRiskEvaluationMethodDto>
     * @author QuCheng Tech
     * @since 2024/7/5
     */
    public List<HazardRiskEvaluationMethodDto> getRiskEvaluationMethods() {
        List<HazardRiskEvaluationMethodDto> result = new ArrayList<>();

        //直接法
        HazardRiskEvaluationMethodDto method1 = new HazardRiskEvaluationMethodDto();
        method1.setMethod(EhsRiskEvaluationMethodEnum.DIRECT.getIndex());
        method1.setName(EhsRiskEvaluationMethodEnum.DIRECT.getName());
        method1.setOptions(new ArrayList<>());

        //LS法
        HazardRiskEvaluationMethodDto method2 = new HazardRiskEvaluationMethodDto();
        method2.setMethod(EhsRiskEvaluationMethodEnum.LS.getIndex());
        method2.setName(EhsRiskEvaluationMethodEnum.LS.getName());
        List<HazardRiskEvaluationOptionsItemDto> itemLS = new ArrayList<>();
        HazardRiskEvaluationOptionsItemDto lsItemL = new HazardRiskEvaluationOptionsItemDto();
        lsItemL.setCode("L");
        lsItemL.setName("L");
        List<KeyValuePairDto> lsItemLOptions = new ArrayList<>();
        KeyValuePairDto lsLKeyValue1 = new KeyValuePairDto();
        lsLKeyValue1.setKey("1");
        lsLKeyValue1.setValue("从未听说过");
        KeyValuePairDto lsLKeyValue2 = new KeyValuePairDto();
        lsLKeyValue2.setKey("2");
        lsLKeyValue2.setValue("在国内曾发生过");
        KeyValuePairDto lsLKeyValue3 = new KeyValuePairDto();
        lsLKeyValue3.setKey("3");
        lsLKeyValue3.setValue("在业内曾发生过");
        KeyValuePairDto lsLKeyValue4 = new KeyValuePairDto();
        lsLKeyValue4.setKey("4");
        lsLKeyValue4.setValue("在公司内发生过");
        KeyValuePairDto lsLKeyValue5 = new KeyValuePairDto();
        lsLKeyValue5.setKey("5");
        lsLKeyValue5.setValue("近一年内发生过");
        lsItemLOptions.add(lsLKeyValue1);
        lsItemLOptions.add(lsLKeyValue2);
        lsItemLOptions.add(lsLKeyValue3);
        lsItemLOptions.add(lsLKeyValue4);
        lsItemLOptions.add(lsLKeyValue5);
        lsItemL.setOptions(lsItemLOptions);
        lsItemL.setPrompt("L—可能性");

        HazardRiskEvaluationOptionsItemDto lsItemS = new HazardRiskEvaluationOptionsItemDto();
        lsItemS.setCode("S");
        lsItemS.setName("S");
        List<KeyValuePairDto> lsItemSOptions = new ArrayList<>();
        KeyValuePairDto lsSKeyValue1 = new KeyValuePairDto();
        lsSKeyValue1.setKey("1");
        lsSKeyValue1.setValue("一般无损伤");
        KeyValuePairDto lsSKeyValue2 = new KeyValuePairDto();
        lsSKeyValue2.setKey("2");
        lsSKeyValue2.setValue("1至2人轻伤");
        KeyValuePairDto lsSKeyValue3 = new KeyValuePairDto();
        lsSKeyValue3.setKey("3");
        lsSKeyValue3.setValue("造成1至2人重伤,3至6人轻伤");
        KeyValuePairDto lsSKeyValue4 = new KeyValuePairDto();
        lsSKeyValue4.setKey("4");
        lsSKeyValue4.setValue("1人死亡,3至6人重伤或严重职业病");
        KeyValuePairDto lsSKeyValue5 = new KeyValuePairDto();
        lsSKeyValue5.setKey("5");
        lsSKeyValue5.setValue("2人以上死亡,7人及以上重伤");
        lsItemSOptions.add(lsSKeyValue1);
        lsItemSOptions.add(lsSKeyValue2);
        lsItemSOptions.add(lsSKeyValue3);
        lsItemSOptions.add(lsSKeyValue4);
        lsItemSOptions.add(lsSKeyValue5);
        lsItemS.setOptions(lsItemSOptions);
        lsItemS.setPrompt("S—后果严重性");

        itemLS.add(lsItemL);
        itemLS.add(lsItemS);
        method2.setOptions(itemLS);
        method2.setLevel1(0);
        method2.setLevel2(4);
        method2.setLevel3(9);
        method2.setLevel4(16);

        //LSC法
        HazardRiskEvaluationMethodDto method3 = new HazardRiskEvaluationMethodDto();
        method3.setMethod(EhsRiskEvaluationMethodEnum.LEC.getIndex());
        method3.setName(EhsRiskEvaluationMethodEnum.LEC.getName());
        List<HazardRiskEvaluationOptionsItemDto> itemLEC = new ArrayList<>();
        HazardRiskEvaluationOptionsItemDto lecItemL = new HazardRiskEvaluationOptionsItemDto();
        lecItemL.setCode("L");
        lecItemL.setName("L");
        List<KeyValuePairDto> lecItemLOptions = new ArrayList<>();
        KeyValuePairDto lecLKeyValue1 = new KeyValuePairDto();
        lecLKeyValue1.setKey("0.1");
        lecLKeyValue1.setValue("实际不可能");
        KeyValuePairDto lecLKeyValue2 = new KeyValuePairDto();
        lecLKeyValue2.setKey("0.2");
        lecLKeyValue2.setValue("极不可能");
        KeyValuePairDto lecLKeyValue3 = new KeyValuePairDto();
        lecLKeyValue3.setKey("0.5");
        lecLKeyValue3.setValue("很不可能,可以设想");
        KeyValuePairDto lecLKeyValue4 = new KeyValuePairDto();
        lecLKeyValue4.setKey("1");
        lecLKeyValue4.setValue("可能性小,完全意外");
        KeyValuePairDto lecLKeyValue5 = new KeyValuePairDto();
        lecLKeyValue5.setKey("3");
        lecLKeyValue5.setValue("可能,但不经常");
        KeyValuePairDto lecLKeyValue6 = new KeyValuePairDto();
        lecLKeyValue6.setKey("6");
        lecLKeyValue6.setValue("相当可能");
        KeyValuePairDto lecLKeyValue7 = new KeyValuePairDto();
        lecLKeyValue7.setKey("10");
        lecLKeyValue7.setValue("完全可以预料");
        lecItemLOptions.add(lecLKeyValue1);
        lecItemLOptions.add(lecLKeyValue2);
        lecItemLOptions.add(lecLKeyValue3);
        lecItemLOptions.add(lecLKeyValue4);
        lecItemLOptions.add(lecLKeyValue5);
        lecItemLOptions.add(lecLKeyValue6);
        lecItemLOptions.add(lecLKeyValue7);
        lecItemL.setOptions(lecItemLOptions);
        lecItemL.setPrompt("L（Likelihood，事故发生的可能性）");

        HazardRiskEvaluationOptionsItemDto lecItemE = new HazardRiskEvaluationOptionsItemDto();
        lecItemE.setCode("E");
        lecItemE.setName("E");
        List<KeyValuePairDto> lecItemEOptions = new ArrayList<>();
        KeyValuePairDto lecEKeyValue1 = new KeyValuePairDto();
        lecEKeyValue1.setKey("0.5");
        lecEKeyValue1.setValue("非常罕见地暴露");
        KeyValuePairDto lecEKeyValue2 = new KeyValuePairDto();
        lecEKeyValue2.setKey("1");
        lecEKeyValue2.setValue("每年几次暴露");
        KeyValuePairDto lecEKeyValue3 = new KeyValuePairDto();
        lecEKeyValue3.setKey("2");
        lecEKeyValue3.setValue("每月一次暴露");
        KeyValuePairDto lecEKeyValue4 = new KeyValuePairDto();
        lecEKeyValue4.setKey("3");
        lecEKeyValue4.setValue("每周一次,或偶尔暴露");
        KeyValuePairDto lecEKeyValue5 = new KeyValuePairDto();
        lecEKeyValue5.setKey("6");
        lecEKeyValue5.setValue("每天工作时间内暴露");
        KeyValuePairDto lecEKeyValue6 = new KeyValuePairDto();
        lecEKeyValue6.setKey("10");
        lecEKeyValue6.setValue("连续暴露");
        lecItemEOptions.add(lecEKeyValue1);
        lecItemEOptions.add(lecEKeyValue2);
        lecItemEOptions.add(lecEKeyValue3);
        lecItemEOptions.add(lecEKeyValue4);
        lecItemEOptions.add(lecEKeyValue5);
        lecItemEOptions.add(lecEKeyValue6);
        lecItemE.setOptions(lecItemEOptions);
        lecItemE.setPrompt("E（Exposure，人员暴露于危险环境中的频繁程度）");

        HazardRiskEvaluationOptionsItemDto lecItemC = new HazardRiskEvaluationOptionsItemDto();
        lecItemC.setCode("C");
        lecItemC.setName("C");
        List<KeyValuePairDto> lecItemCOptions = new ArrayList<>();
        KeyValuePairDto lecCKeyValue1 = new KeyValuePairDto();
        lecCKeyValue1.setKey("1");
        lecCKeyValue1.setValue("引人注目,需要救护");
        KeyValuePairDto lecCKeyValue2 = new KeyValuePairDto();
        lecCKeyValue2.setKey("3");
        lecCKeyValue2.setValue("重大,致残");
        KeyValuePairDto lecCKeyValue3 = new KeyValuePairDto();
        lecCKeyValue3.setKey("7");
        lecCKeyValue3.setValue("严重,重伤");
        KeyValuePairDto lecCKeyValue4 = new KeyValuePairDto();
        lecCKeyValue4.setKey("15");
        lecCKeyValue4.setValue("非常严重,一人死亡");
        KeyValuePairDto lecCKeyValue5 = new KeyValuePairDto();
        lecCKeyValue5.setKey("40");
        lecCKeyValue5.setValue("难,数人死亡");
        KeyValuePairDto lecCKeyValue6 = new KeyValuePairDto();
        lecCKeyValue6.setKey("100");
        lecCKeyValue6.setValue("大灾难,许多人死亡");
        lecItemCOptions.add(lecCKeyValue1);
        lecItemCOptions.add(lecCKeyValue2);
        lecItemCOptions.add(lecCKeyValue3);
        lecItemCOptions.add(lecCKeyValue4);
        lecItemCOptions.add(lecCKeyValue5);
        lecItemCOptions.add(lecCKeyValue6);
        lecItemC.setOptions(lecItemCOptions);
        lecItemC.setPrompt("C（Consequence，一旦发生事故可能造成的后果）");

        itemLEC.add(lecItemL);
        itemLEC.add(lecItemE);
        itemLEC.add(lecItemC);
        method3.setOptions(itemLEC);
        method3.setLevel1(0);
        method3.setLevel2(70);
        method3.setLevel3(160);
        method3.setLevel4(320);

        result.add(method1);
        result.add(method2);
        result.add(method3);
        return result;
    }

    /**
     * 评价指定危险源风险
     *
     * @param dto      风险评价信息对象
     * @param userInfo 当前操作用户信息，需要获取里面的用户ID和名称
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @description 保存指定危险源的风险评价结果;保存评价记录后需要对危险源信息表中的风险等级进行更新；对单元中的危险源数量统计进行更新；
     * @since 2024/11/5
     */
    public String evaluationRisk(HazardRiskEvaluationDto dto, UacUserInfoDto userInfo) throws QCPromptException {
        //1.DTO有效性验证
        if (dto == null) return QCUnifyReturnValue.Warn("请求对象不能为空");
        if (StringUtils.isBlank(dto.getHazardid())) return QCUnifyReturnValue.Warn("危险源ID不能为空");
        if (StringUtils.isBlank(dto.getTm())) return QCUnifyReturnValue.Warn("评价时间不能为空");

        //评价时间处理
        Date evaluationDate = null;
        if (StringUtils.isNotBlank(dto.getTm())) {
            try {
                evaluationDate = DateUtil.parseDate(dto.getTm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("评价时间转换错误");
            }
        }

        if (evaluationDate.after(DateUtil.getNowDate()))
            return QCUnifyReturnValue.Warn("风险评价时间不能大于当前时间。");
        dto.setTm(null);

        //2.DTO -> ENTITY
        EhsHazardRiskEvaluation evaluationEntity = EhsHazardRiskEvaluationMapper.MAPPER.dtoToEntity(dto);
        evaluationEntity.setTm(evaluationDate);

        //3.获取指定危险源信息，保存评价记录后对危险源信息表中的风险等级进行更新
        EhsHazardInfo hazardInfo = hazardInfoRepository.selectById(dto.getHazardid());

        //4.获取指定单元信息，对单元中的危险源数量统计进行更新；
        EhsUnitInfo unitInfo = unitInfoRepository.selectById(hazardInfo.getUnitid());
        Integer general1 = unitInfo.getGeneral1() == null ? 0x0 : unitInfo.getGeneral1(),
                major1 = unitInfo.getMajor1() == null ? 0x0 : unitInfo.getMajor1(),
                level11 = unitInfo.getLevel11() == null ? 0x0 : unitInfo.getLevel11(),
                level12 = unitInfo.getLevel12() == null ? 0x0 : unitInfo.getLevel12(),
                level13 = unitInfo.getLevel13() == null ? 0x0 : unitInfo.getLevel13(),
                level14 = unitInfo.getLevel14() == null ? 0x0 : unitInfo.getLevel14(),
                general2 = unitInfo.getGeneral2() == null ? 0x0 : unitInfo.getGeneral2(),
                major2 = unitInfo.getMajor2() == null ? 0x0 : unitInfo.getMajor2(),
                level21 = unitInfo.getLevel21() == null ? 0x0 : unitInfo.getLevel21(),
                level22 = unitInfo.getLevel22() == null ? 0x0 : unitInfo.getLevel22(),
                level23 = unitInfo.getLevel23() == null ? 0x0 : unitInfo.getLevel23(),
                level24 = unitInfo.getLevel24() == null ? 0x0 : unitInfo.getLevel21();

        //5.指定单元中的危险源数量统计
        //根据指定危险源的辨识结果判断当前危险源为第一类危险源还是第二类危险源，再根据原记录风险等级分别统计风险等级数量 - 1
        //根据辨识结果判断当前危险源为第一类危险源还是第二类危险源，再根据当前风险等级分别统计风险等级数量 + 1
        if (hazardInfo.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HAZARD) {
            //第一类危险源
            //原有风险等级数量--，现有风险等级数量++
            if (hazardInfo.getRisklevel() != null) {
                if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.LOW) level11 -= 0x1;
                else if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.GENERAL) level12 -= 0x1;
                else if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.GREATER) level13 -= 0x1;
                else if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.MAJOR) level14 -= 0x1;
            }
            if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.LOW) level11 += 0x1;
            else if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.GENERAL) level12 += 0x1;
            else if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.GREATER) level13 += 0x1;
            else if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.MAJOR) level14 += 0x1;
        } else if (hazardInfo.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HIDDEN_TROUBLE) {
            //第二类危险源
            //原有风险等级数量--，现有风险等级数量++
            if (hazardInfo.getRisklevel() != null) {
                if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.LOW) level21 -= 0x1;
                else if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.GENERAL) level22 -= 0x1;
                else if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.GREATER) level23 -= 0x1;
                else if (hazardInfo.getRisklevel() == EhsRiskLevelEnum.MAJOR) level24 -= 0x1;
            }
            if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.LOW) level21 += 0x1;
            else if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.GENERAL) level22 += 0x1;
            else if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.GREATER) level23 += 0x1;
            else if (evaluationEntity.getRisklevel() == EhsRiskLevelEnum.MAJOR) level24 += 0x1;
        } else {
            //不存在
        }

        //6.新增/修改危险源风险评价记录信息：
        // 防止同一天多次操作产生多条记录：对风险评价时间进行控制，暂时精确到日。针对同一危险源在一天内多次保存，只保留最新风险评价时间的评价记录。
        //查询当前危险源的当日危险源评价记录，如果有危险源评价记录，则更新评价记录，否则新增危险源评价记录。
        LambdaQueryWrapper<EhsHazardRiskEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsHazardRiskEvaluation::getHazardid, dto.getHazardid())
                .likeRight(EhsHazardRiskEvaluation::getTm, DateUtil.getDateString(DateUtil.getNowDate()));
        EhsHazardRiskEvaluation evaluation = repository.selectOne(wrapper);
        evaluationEntity.setTm(evaluationDate);
        evaluationEntity.setIntm(DateUtil.getNowDate());
        evaluationEntity.setInuserid(userInfo.getId());
        evaluationEntity.setInusername(userInfo.getName());
        if (Objects.nonNull(evaluation)) {
            //当前危险源当日有评价记录，更新评价记录
            evaluationEntity.setEvlid(evaluation.getEvlid());
            repository.updateById(evaluationEntity);
        } else {
            //当前危险源当日没有评价记录，新增评价记录
            evaluationEntity.setEvlid(IdentifierUtil.randomUUID());
            if (repository.insert(evaluationEntity) < 0x1) {
                return QCUnifyReturnValue.Warn("保存风险评价记录失败");
            }
        }

        //7.更新指定危险源信息中的风险等级
        hazardInfo.setEvltm(evaluationDate);
        hazardInfo.setRisklevel(evaluationEntity.getRisklevel());
        hazardInfoRepository.updateById(hazardInfo);

        //保存评价后对隐患治理表中的对应隐患的风险等级进行更新；
        //要求同时满足以下情况：
        //保存评价风险等级的危险源为第二类危险源；
        //隐患治理表中对应危险源ID的整改完成和验收通过均为false；
        if (hazardInfo.getIdentificationresult() == EhsHazardIndentificationResultTypeEnum.HIDDEN_TROUBLE) {
            //在保存风险等级评价后对隐患治理表中未整改完的隐患同步更新风险等级；
            //根据危险源ID查询隐患治理记录
            List<EhsTroubleCorrectInfoDto> troubleCorrectInfoDtos = troubleCorrectService.getByHazard(hazardInfo.getHazardid());
            if (CollectionUtils.isNotEmpty(troubleCorrectInfoDtos)) {
                List<EhsTroubleCorrectInfoDto> correctInfoDtos = troubleCorrectInfoDtos.stream().filter(p ->
                        !p.isHascorrect() && !p.isHascheck()).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(correctInfoDtos)) {
                    List<String> correctids = correctInfoDtos.stream()
                            .map(EhsTroubleCorrectInfoDto::getCorrectid).collect(Collectors.toList());
                    troubleCorrectService.updateRiskLevel(correctids, dto.getRisklevel());
                }
            }

        }

        //8.更新单元信息中的危险源数量
        unitInfo.setGeneral1(general1);
        unitInfo.setMajor1(major1);
        unitInfo.setLevel11(level11);
        unitInfo.setLevel12(level12);
        unitInfo.setLevel13(level13);
        unitInfo.setLevel14(level14);
        unitInfo.setGeneral2(general2);
        unitInfo.setMajor2(major2);
        unitInfo.setLevel21(level21);
        unitInfo.setLevel22(level22);
        unitInfo.setLevel23(level23);
        unitInfo.setLevel24(level24);
        unitInfoRepository.updateById(unitInfo);
        //更新当前单元的父级单元信息(直到根节点)
        unitInfoService.modifyParentUnit(unitInfo);

        return QCUnifyReturnValue.Success();
    }

    /**
     * 获取指定危险源最新评价记录
     *
     * @param id 危险源ID
     * @return HazardRiskEvaluationDto
     * @author QuCheng Tech
     * @since 2024/11/8
     */
    public HazardRiskEvaluationDto latest(String id) {
        LambdaQueryWrapper<EhsHazardRiskEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsHazardRiskEvaluation::getHazardid, id)
                .orderByDesc(EhsHazardRiskEvaluation::getTm);
        EhsHazardRiskEvaluation en = repository.selectOne(wrapper);
        if (Objects.nonNull(en)) {
            return EhsHazardRiskEvaluationMapper.MAPPER.toDto(en);
        }
        return null;
    }

    /**
     * 查询指定组织中指定时间段内的危险源辨识记录集合
     *
     * @param orgCode   组织机构代码
     * @param beginTime 起始时间
     * @param endTime   截止时间
     * @author QuCheng Tech
     */
    public List<EhsHazardRiskEvaluation> geAllRiskevl(String orgCode, Date beginTime, Date endTime) throws QCPromptException {
        //SQL 查询的目的是查询两个表（EHS_HAZARD_RISKEVL 风险评价记录表和 ehs_hazard_info 危险源信息表）中有记录的危险源信息，并根据以下条件过滤结果：
        //1.只返回指定组织机构的记录。
        //2.只返回辨识时间在指定查询时间范围内的记录。
        MPJLambdaWrapper<EhsHazardRiskEvaluation> wrapper = new MPJLambdaWrapper<EhsHazardRiskEvaluation>()
                // 字段关联
                .innerJoin(EhsHazardInfo.class, EhsHazardInfo::getHazardid, EhsHazardRiskEvaluation::getHazardid)
                // 组织机构代码，必须有，判断相等 
                .eq(EhsHazardInfo::getOrgcode, orgCode)
                // 时间范围过滤
                .ge(EhsHazardRiskEvaluation::getTm, beginTime)
                .le(EhsHazardRiskEvaluation::getTm, endTime);
        return repository.selectJoinList(EhsHazardRiskEvaluation.class, wrapper);
    }

    /**
     * 查询指定单元的风险评价记录，按风险评价时间降序返回
     *
     * @param unitid    单元ID
     * @param beginTime 起始时间
     * @param endTime   截止时间
     * @return java.util.List<qc.module.ehs.dto.hazardidentity.HazardRiskEvaluationDto>
     * @author QuCheng Tech
     * @since 2025/6/11
     */
    public List<HazardRiskEvaluationDto> queryByUnit(String unitid, Date beginTime, Date endTime) {
        //由于只指定了单元ID，需要做连接查询，根据单元ID查询危险源ID集合
        MPJLambdaWrapper<EhsHazardRiskEvaluation> wrapper = new MPJLambdaWrapper<>();
        //指定查询内容，一个select只能查一个表
        //查危险源名称
        //wrapper.select(EhsHazardInfo::getHazardname);
        //取危险源信息表中的title作为危险源名称
        wrapper.select("t1.title as hazardname");//Wrapper中实体类对应表为t，连接的另外一张表为t1
        //查风险评价表
        wrapper.selectAll(EhsHazardRiskEvaluation.class);
        //连接危险源信息表
        wrapper.leftJoin(EhsHazardInfo.class, EhsHazardInfo::getHazardid, EhsHazardRiskEvaluation::getHazardid);
        //指定单元
        wrapper.eq(EhsHazardInfo::getUnitid, unitid);
        //指定风险评价时间
        wrapper.ge(EhsHazardRiskEvaluation::getTm, beginTime)
                .le(EhsHazardRiskEvaluation::getTm, endTime);

        //排按风险评价时间降序返回
        wrapper.orderByDesc(EhsHazardRiskEvaluation::getTm);

        return repository.selectJoinList(HazardRiskEvaluationDto.class, wrapper);
    }

    /**
     * 查询指定单元的风险评价Entity集合
     *
     * @param unitid    单元ID
     * @param beginTime 起始时间
     * @param endTime   截止时间
     * @return java.util.List<qc.module.ehs.entity.EhsHazardRiskEvaluation>
     * @author QuCheng Tech
     * @since 2025/6/13
     */
    public List<EhsHazardRiskEvaluation> queryUnitRiskevlEntities(String unitid, Date beginTime, Date endTime) throws QCPromptException {
        MPJLambdaWrapper<EhsHazardRiskEvaluation> wrapper = new MPJLambdaWrapper<>();
        //查风险评价表
        wrapper.selectAll(EhsHazardRiskEvaluation.class);
        //连接危险源信息表
        wrapper.leftJoin(EhsHazardInfo.class, EhsHazardInfo::getHazardid, EhsHazardRiskEvaluation::getHazardid);
        //指定单元
        wrapper.eq(EhsHazardInfo::getUnitid, unitid);
        //指定风险评价时间
        wrapper.ge(EhsHazardRiskEvaluation::getTm, beginTime)
                .le(EhsHazardRiskEvaluation::getTm, endTime);

        //排按风险评价时间降序返回
        wrapper.orderByDesc(EhsHazardRiskEvaluation::getTm);

        return repository.selectJoinList(EhsHazardRiskEvaluation.class, wrapper);
    }
}
